const { Users } = require('../models')
const crud = require('./crudUtil')
const jwt = require('jsonwebtoken')

//添加用户
const userAdd = async ctx => {
    let { username = '', pwd = '' } = ctx.request.body
    await crud.add(User, { username, pwd }, ctx)
}
//修改用户
const userUpdate = async ctx => {
    let params = ctx.request.body
    await crud.update(User, params, ctx)
}
// 删除用户
const userDel = async ctx => {
    let _id = ctx.request.body
    await crud.del(User, _id, ctx)
}
//查询所有用户
const userFind = async ctx => {
    await crud.find(User, null, ctx)
}
//查询单个用户
const userFindOne = async ctx => {
    let _id = ctx.params.id
    await crud.findOne(User, _id, ctx)
}

//用户登录
const login = async ctx => {
    let { username, pwd } = ctx.request.body
    await Users.findOne({ username, pwd }).then(rel => {
        if (rel) {
            let token = jwt.sign({
                username,
                _id: rel._id
            }, 'jianshu-server-jwt', {
                expiresIn: 3600 * 24 * 7
            })
            ctx.body = {
                code: 200,
                msg: '登录成功',
                token,
                result: rel
            }
        } else {
            ctx.body = {
                code: 300,
                msg: '登录失败',
            }

        }
    }).catch(err => {
        ctx.body = {
            code: 500,
            msg: '登录时出现异常',
            err
        }
    })
}
//用户注册
const reg = async ctx => {
    let { username, pwd } = ctx.request.body
    let isDouble = false
    await Users.findOne({ username }).then(rel => {
        if (rel) isDouble = true
    })
    if(isDouble) {
        ctx.body = {
            code: 300,
            msg: '用户名已存在'
        }
        return 
    }
    await Users.create({username, pwd}).then(rel => {
        if (rel) {
            ctx.body = {
                code: 200,
                msg: '注册成功'
            }
        } else {
            ctx.body = {
                code: 300,
                msg: '注册失败',
            }
        }

    }).catch(err => {
        ctx.body = {
            code: 500,
            msg: '注册时出现异常',
            err
        }
    })
}
/**
 * 验证用户登录
 */
const verify = async ctx => {
    let token = ctx.header.authorization
    token = token.replace('Bearer ', '')
    try{
        let result = jwt.verify(token, 'jianshu-server-jwt')
        await Users.findOne({_id: result._id}).then(rel => {
            if(rel) {
                ctx.body = {
                    code: 200,
                    msg: '用户验证成功',
                    user: rel
                }
            }else {
                ctx.body = {
                    code: 500,
                    msg: '用户验证失败'
                }
            }
        }).catch(err => {
            ctx.body = {
                code: 500,
                msg: '用户验证失败'
            }
        })
    }catch(err) {
        ctx.body = {
            code: 500,
            msg: '用户验证失败'
        }
    }
}
/**
 * 修改用户密码
 */
const updatepwd = async ctx => {
    let { username, pwd} = ctx.request.body
    await Users.updateOne({username}, { pwd }).then(rel => {
        console.log(rel);
        if(rel.modifiedCount > 0) {
            ctx.body = {
                code: 200,
                msg: '修改密码成功'
            }
        }else {
            ctx.body = {
                code: 300,
                msg: '修改密码失败'
            }
        }
    }).catch(err => {
        ctx.body = {
            code: 200,
            msg: '修改密码异常',
            err
        }
    })
}
/**
 * 修改用户资料 
 */
const updatePersonal = async ctx=> {
    let user = ctx.request.body
    await Users.updateOne(
        { _id: user._id },
        {
            avatar: user.avatar,
            sex: user.sex,
            desc: user.desc,
            phone: user.phone,
            email: user.email
        }
    ).then(rel => {
        if(rel.modifiedCount > 0) {
            ctx.body = {
                code: 200,
                msg: "资料已更新"
            }
        }else {
            ctx.body = {
                code: 300,
                msg: "资料更新失败"
            }
        }
    }).catch(err => {
        ctx.body = {
            code: 300,
            msg: '资料更新时出现异常'
        }
        console.log(err);
    })
}

module.exports = {
    userAdd,
    userUpdate,
    userDel,
    userFind,
    userFindOne,
    login,
    reg,
    verify,
    updatepwd,
    updatePersonal
}

